// context/CounterContext.tsx
import React, { createContext, useContext, useReducer } from 'react';

// types/counter.ts
export type CounterState = {
    serverId: number | string;
    serverName: string;
    serverList: {
        id: string | number;
        name: string;
    }[];
};

export type CounterAction = {
    type: 'SET_COUNT'; payload: {
        serverId?: number | string;
        serverName?: string;
        serverList?: {
            id: string | number;
            name: string;
        }[]
    },
};

export const initialState: CounterState = {
    serverId: '',
    serverName: '',
    serverList: [],
};

// reducers/counterReducer.ts
export const counterReducer = (
    state: CounterState,
    action: CounterAction
): CounterState => {
    switch (action.type) {
        case 'SET_COUNT':
            return { ...state, ...action.payload };
        default:
            return state;
    }
};

// 定义 Context 类型
type CounterContextType = {
    state: CounterState;
    dispatch: React.Dispatch<CounterAction>;
};

// 创建 Context
const CounterContext = createContext<CounterContextType | undefined>(undefined);

// Provider 组件
export const CounterProvider: React.FC<{ children: React.ReactNode }> = ({ children }) => {
    const [state, dispatch] = useReducer(counterReducer, initialState);

    return (
        <CounterContext.Provider value={{ state, dispatch }}>
            {children}
        </CounterContext.Provider>
    );
};

// 自定义 Hook 获取 Context
export const useCounter = () => {
    const context = useContext(CounterContext);
    if (!context) {
        throw new Error('useCounter must be used within a CounterProvider');
    }
    return context;
};